package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SendMsgUtil;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.dto.LoginDto;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author:YZN
 * @date:2023/1/7
 * @description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody LoginDto dto){
        //参数校验
        if (StringUtils.isBlank(dto.getPhone())){
            return R.error("请输入手机号");
        }
        //生成验证码
        String code = UUID.randomUUID().toString().replace("-","").substring(0,6);
        System.out.println("验证码为"+code);

        //调用sendmsgutil
        //SendMsgUtil.sendMsg(dto.getPhone(),code);
        //存储验证码
        //request.getSession().setAttribute(dto.getPhone(),code);
        redisTemplate.opsForValue().set(dto.getPhone(),code);
        redisTemplate.expire(dto.getPhone(),5L, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginDto dto){
        //参数校验
        if (null == dto){
            return R.error("参数错误");
        }
        //验证码校验
        //String code  = (String) request.getSession().getAttribute(dto.getPhone());
        String code  = (String) redisTemplate.opsForValue().get(dto.getPhone());
        if (StringUtils.isBlank(code)){
            return R.error("请先获取验证码");
        }
        if ( !code.equalsIgnoreCase(dto.getCode())){
            return R.error("验证码错误");
        }
        User user = userService.loginUser(dto.getPhone());

        //将用户ID存入session 方便后期使用
        request.getSession().setAttribute("user",user.getId());
        //登录成功后,删除session中的验证码
        //request.getSession().removeAttribute(dto.getPhone());
        redisTemplate.delete(dto.getPhone());
        return R.success("登录成功");
    }

    @PostMapping("/loginout")
    public R loginout(){
        request.getSession().removeAttribute("user");
        return R.success("登出成功");
    }
}
